<template>
  <div class="purchase_view">
    <!-- 添加或修改申请采购明细对话框 -->
    <el-dialog :title="title" center :visible.sync="open" width="960px" append-to-body>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="流程表单" name="first"></el-tab-pane>
      <el-tab-pane label="流程导入" name="second" v-if="detailsList.length>0">
        <FlowChoose ref="workFlow" @workflow="setWorkflow" :businessType="form.businessTypeOpt"></FlowChoose>
      </el-tab-pane>
    </el-tabs>
       <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="activeName=='first'">
        <el-form-item style="margin-top: 0" label="流程创建" prop="createUserId">
          <span style="color: #0000ee">{{form.createTime}} {{form.createBy}}创建</span>
          <div style="float:right;">
              <el-button
             :class="showCopy?'dis_active':'active'"
            type="text"
            @click="showCopy=showCopy?false:true"
          >新建抄送</el-button>
            </div>
        </el-form-item>
        <el-form-item label="流程名称" prop="flowName">
          <el-input  placeholder="请输入流程名称" size="small" v-model="form.flowName"/>
        </el-form-item>
        <el-form-item label="任务抄送" prop="copyToUsers" v-show="showCopy">
          <div class="purchase_s_view">
            <el-input style="width: 100%" v-model="choosedUserName" placeholder="抄送人员" class="form_long"/>
			<el-button type="primary" @click="selectUser" plain>选择用户</el-button>
          </div>
        </el-form-item>
        <el-form-item label="申购清单" prop="createUserId" v-if="activeName=='first' && form.instanceId>0">
          <div style="float:right;" class="purchase_s_view">
              <CollegeDialog v-if="isAcademy" @list ="getList" :purchaseId="form.instanceId"></CollegeDialog>
              <TeacherDialog v-if="!isAcademy" @list ="getList" ref="teacherDialog" :instanceId="form.instanceId" :kindsOptions="kindsOptions" :unitOptOptions="unitOptOptions" ></TeacherDialog>
            </div>
        </el-form-item>
      </el-form>

      <el-table style="width: 100%; margin-bottom: 20px; margin-top: -15px" :data="detailsList" v-if="activeName=='first' && form.instanceId>0">
          <el-table-column label="编号" align="center" prop="purchaseDetailId" width="60"/>
          <el-table-column label="申购工号" align="center" prop="applyTeacher" width="80" :show-overflow-tooltip="true"/>
          <el-table-column label="名称"  prop="materialName" :show-overflow-tooltip="true"/>
		  <el-table-column label="Cas号" align="center" prop="casNo" width="80" :show-overflow-tooltip="true"/>
          <el-table-column label="类别" align="center" prop="hazardousOpt" width="80" :formatter="kindsFormat" :show-overflow-tooltip="true"/>
          <el-table-column label="数量" align="center" prop="quantity" width="60"/>
          <el-table-column label="单位" align="center" prop="unitOpt" :formatter="unitOptFormat" width="60"/>
          <el-table-column label="厂家"  prop="recommendedManufacturer" width="100" :show-overflow-tooltip="true"/>
          <el-table-column label="货号" align="center" prop="orderCode" width="80"/>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" width="100"/>
          <el-table-column label="操作" align="center" width="80" v-if="!isAcademy">
            <template slot-scope="scope">
                <el-button
                  size="mini"
                  class="active"
                  type="text"
                  style="margin-left: 5px"
                  @click="handleUpdateDetail(scope.row)"
                  v-hasPermi="['labdata:casInventory:edit']"
                >编辑</el-button>
                <el-button
                  size="mini"
                  class="active"
                  type="text"
                  style="margin-left: 5px"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['labdata:casInventory:edit']"
                >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0 && activeName=='first'"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="activeName=='first'"  v-hasPermi="['labdanger:purchase:edit']">保存</el-button>
        <el-button type="primary" @click="submitWorkflow" v-if="activeName=='second'"  v-hasPermi="['labdanger:purchase:edit']">提交</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
	<ChooseUser @chooseUsers="getUser" ref="checkedUserCom"></ChooseUser>
  </div>
</template>

<script>
import { getCheckedList } from "@/api/labdata/employee";
import {getAllRestrictedKinds} from "@/api/labdata/cylindersType";
import { getPurchase, addPurchase, updatePurchase,submitPurchase } from "@/api/labdanger/purchase";
import { list, delCas} from "@/api/labdanger/purchaseDet.js";
import ChooseUser from "@/views/labdata/employee/user_choose_com.vue";
import CollegeDialog from './purchase/collegeDialog.vue';
import TeacherDialog from './purchase/teacherDialog.vue';
import FlowChoose from '@/views/labdata/flowDefination/flow_choose.vue'
import { formatCurrentDate } from "@/utils/index";
export default {
  components: {
    ChooseUser,
    CollegeDialog,
    TeacherDialog,
    FlowChoose
  },
  name: "PurchaseDialog",
  data() {
    return {
      isAcademy:false,
      checkedUserList:[],
      choosedUserName:'',
      activeName: 'first',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      showCopy: false,
      // 申请采购明细表格数据
      detailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 申请状态字典
      applyStatusOptOptions: [],
      // 类别字典
      kindsOptions: [],
      // 单位字典
      unitOptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        instanceId: null,
      },
      // 表单参数
      form: {},
      editItem: {},
      // 表单校验
      rules: {
        flowName: [
            { required: true, message: "申请名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    //console.log('user:'+JSON.stringify(this.$store.state.user));
    this.getAllKinds();
    this.getDicts("unitOpt").then(response => {
         this.unitOptOptions = response.data;
       });
  },
  watch:{
    checkedUserList :function(val){
      this.choosedUserName = '';
      this.form.copyToUsers = '';
      val.forEach((item, index)=>{
        if(index>0){
          this.choosedUserName +=",";
          this.form.copyToUsers +=",";
        }
        this.choosedUserName += item.nickName;
        this.form.copyToUsers += item.userId;
      })
    },
  },
  computed:{

  },
  methods: {
    setWorkflow(workflowId){
      this.form.workflowId = workflowId;
      //console.log('workflow='+workflowId);
    },
    submitWorkflow(){
		if(!this.form.workflowId){
		  this.form.workflowId = this.$refs["workFlow"].getWorkflowId();
		}
        submitPurchase(this.form).then(response => {
          this.msgSuccess("修改成功");
          this.open = false;
          this.$emit("refresh");
        });
    },
    getAllKinds(){
      getAllRestrictedKinds().then(response => {
        this.kindsOptions = response.data;
      });
    },
    kindsFormat(row, column){
      for(let i=0; i<this.kindsOptions.length;i++){
        if(this.kindsOptions[i].kindsId == row.hazardousOpt){
          return this.kindsOptions[i].name;
        }
      }
      return '';
    },
    // 单位字典翻译
    unitOptFormat(row, column) {
      return this.selectDictLabel(this.unitOptOptions, row.unitOpt);
    },
    getList() {
      this.loading = true;
      if(this.isAcademy){
        this.queryParams.purchaseId = this.queryParams.instanceId;
      }
      list(this.queryParams).then(response => {
        this.detailsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$emit("refresh");
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
	  this.checkedUserList = [];
      this.form = {};
      this.resetForm("form");
      this.isAcademy = false;
      this.showCopy = false;
      this.activeName = 'first';
      this.detailsList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(busiType) {
      this.reset();
      if(busiType=='academy'){
        this.isAcademy = true;
      }
      this.form.createTime  = formatCurrentDate();
      this.form.createBy = this.$store.state.user.name;
      this.open = true;
      if(this.isAcademy){
        this.title = "新建危化品采购";
      }else{
        this.title = "新建危化品申购";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
       this.reset();
       this.open = true;
        const instanceId = row.instanceId ;
        getPurchase(instanceId).then(response => {
          this.form = response.data;
          if(this.form.applyOwnerOpt=='academy'){
            this.isAcademy = true;
          }
          if(this.form.copyToUsers!=null){
            getCheckedList({checkedUserIds:this.form.copyToUsers}).then(res=>{
              if(res.data && res.data!=''){
                this.checkedUserList = res.data;
                this.showCopy = true;
              }
            });
          }
          this.queryParams.instanceId =instanceId;
          this.title = "修改申请采购";
          this.getList();
        });
    },
    handleUpdateDetail(row){
      this.$refs["teacherDialog"].updateDetail(row);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.instanceId != null) {
            updatePurchase(this.form).then(response => {
              this.msgSuccess("修改成功");
              if(this.detailsList.length>0){
                this.activeName = 'second';
              }
            });
          } else {
            if(this.isAcademy){
              this.form.applyOwnerOpt = 'academy';
            }else{
              this.form.applyOwnerOpt = 'teacher';
            }
            addPurchase(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.form = response.data;
              this.queryParams.instanceId =this.form.instanceId;
              this.$forceUpdate();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseDetailIds = row.purchaseDetailId || this.ids;
      this.$confirm('是否确认删除编号为"' + purchaseDetailIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCas(purchaseDetailIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    handleTabClick(e) {

    },
    getUser(e) {
      //console.log(JSON.stringify(e));
      this.checkedUserList = e;
    },
	selectUser(){
		if(this.checkedUserList&& this.checkedUserList.length>0){
			this.$refs["checkedUserCom"].handleAdd(this.checkedUserList);
		}else{
			 this.$refs["checkedUserCom"].handleAdd();
		}
	},
  }
};
</script>

<style scoped lang="scss">
 /deep/.el-button.active{
    text-decoration: underline;
    color: #0000ee;
  }
 /deep/ .el-button.dis_active {
    color: #999999
  }
  /*.el-form-item {
    margin-top: -10px;
  }*/
  .purchase_s_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

</style>
